package com.example.testproj.lrucache;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.util.Log;
import android.widget.ImageView;

import com.example.testproj.base.MyApplication;

import java.io.InputStream;

/**
 * @des:
 * @author: 芮勤
 * @date: 2019/8/8 17:23
 * @see {@link }
 */
public class ImageUtils {
    public static Bitmap compressImage(InputStream inputStream, ImageView imageView){
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        BitmapFactory.decodeStream(inputStream,null,options);

        options.inSampleSize= computeScaleSize(imageView, options);
        options.inJustDecodeBounds=false;
        Rect rect=new Rect(0,0,imageView.getMeasuredWidth(),imageView.getMeasuredHeight());
        return  BitmapFactory.decodeStream(inputStream,rect,options);
    }
    public static Bitmap compressImage(int  ResId, ImageView imageView){
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        BitmapFactory.decodeResource(MyApplication.getInstance().getResources(),ResId,options);

        options.inSampleSize= computeScaleSize(imageView, options);
        options.inJustDecodeBounds=false;
        Rect rect=new Rect(0,0,imageView.getMeasuredWidth(),imageView.getMeasuredHeight());
        return   BitmapFactory.decodeResource(MyApplication.getInstance().getResources(),ResId,options);
    }
    private static int  computeScaleSize(ImageView imageView, BitmapFactory.Options options) {
        int imgWidth= imageView.getMeasuredWidth();
        int imgHeight= imageView.getMeasuredHeight();

        if (imgWidth==0&&imgHeight==0){
            return 1;
        }


        int scaleWidth=Math.round(((float) options.outWidth)/imgWidth);
        int scaleHeight=Math.round(((float)options.outHeight)/imgHeight);

        int scaleSize=scaleHeight>scaleWidth?scaleWidth:scaleHeight;
        Log.d("FilleUtils", "computeScaleSize: "+scaleSize);
        Log.d("FilleUtils", "imgWidth: "+imgWidth);
        Log.d("FilleUtils", "options: "+options.outWidth);
        return scaleSize;
    }
}
